﻿DSFA = {};
var isMSIE = $.browser.msie;

$.support.cors = true;
$.ajaxSetup({
    cache: false
});

//jquery扩展函数 开始============================

//生成GUID 开始================
$.newGuid = function (format) {
    function Guid(g) {
        var arr = new Array(); //存放32位数值的数组
        if (typeof (g) == "string") { //如果构造函数的参数为字符串
            InitByString(arr, g);
        }

        else {
            InitByOther(arr);
        }
        //返回一个值，该值指示 Guid 的两个实例是否表示同一个值。
        this.Equals = function (o) {
            if (o && o.IsGuid) {
                return this.ToString() == o.ToString();
            }
            else {
                return false;
            }

        }

        //Guid对象的标记
        this.IsGuid = function () { }
        //返回 Guid 类的此实例值的 String 表示形式。
        this.ToString = function (format) {
            if (typeof (format) == "string") {
                if (format == "N" || format == "D" || format == "B" || format == "P") {
                    return ToStringWithFormat(arr, format);
                }
                else {
                    return ToStringWithFormat(arr, "D");
                }

            }

            else {
                return ToStringWithFormat(arr, "D");
            }

        }

        //由字符串加载
        function InitByString(arr, g) {
            g = g.replace(/\{|\(|\)|\}|-/g, "");
            g = g.toLowerCase();
            if (g.length != 32 || g.search(/[^0-9,a-f]/i) != -1) {
                InitByOther(arr);
            }
            else {
                var temp = g.split("");
                for (var i = 0; i < temp.length; i++) {
                    arr.push(temp[i]);
                }
                //                for (var i = 0; i < g.length; i++) {
                //                    var chat = g[i] || g.substr(i, 1)
                //                    arr.push(chat);
                //                }
            }
        }

        //由其他类型加载

        function InitByOther(arr) {
            var i = 32;
            while (i--) {
                arr.push("0");
            }
        }

        /*

        根据所提供的格式说明符，返回此 Guid 实例值的 String 表示形式。

        N  32 位： xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        D  由连字符分隔的 32 位数字 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 

        B  括在大括号中、由连字符分隔的 32 位数字：{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} 

        P  括在圆括号中、由连字符分隔的 32 位数字：(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) 

        */
        function ToStringWithFormat(arr, format) {
            switch (format) {
                case "N":
                    return arr.toString().replace(/,/g, "");
                case "D":
                    var str = arr.slice(0, 8) + "-" + arr.slice(8, 12) + "-" + arr.slice(12, 16) + "-" + arr.slice(16, 20) + "-" + arr.slice(20, 32);
                    str = str.replace(/,/g, "");
                    return str;
                case "B":
                    var str = ToStringWithFormat(arr, "D");
                    str = "{" + str + "}";
                    return str;
                case "P":
                    var str = ToStringWithFormat(arr, "D");
                    str = "(" + str + ")";
                    return str;
                default:
                    return new Guid();
            }

        }

    }

    //Guid 类的默认实例，其值保证均为零。
    Guid.Empty = new Guid();
    //初始化 Guid 类的一个新实例。
    Guid.NewGuid = function () {
        var g = "";
        var i = 32;
        while (i--) {
            g += Math.floor(Math.random() * 16.0).toString(16);
        }
        return new Guid(g);
    }
    format = format || 'n';
    return Guid.NewGuid().ToString(format.toUpperCase());
}

//生成GUID 结束================

//$.isEmptyObject = function (obj) {
//    for (var name in obj) {
//        return false;
//    }
//    return true;
//}

$.findParentElement=function (curEl, tag) {
    var e = curEl;
    tag = tag.toUpperCase();
    while (e.tagName != tag) {
        if (!e.parentNode) {
            return null;
        }
        e = e.parentNode;
    }
    if (e.tagName == tag) {
        return e;
    }
    else {
        return null;
    }
}

$.setElementAttribute = function (el, attr) {
    for (var key in attr) {
        el.setAttribute(key, attr[key]);
    }
}

//数组检索扩展
$.inArrayEx = function (value, array, fn) {
    if (fn && $.isFunction(fn)) {
        for (var i = 0; i < array.length; i++) {
            if (fn(value, array[i])) {
                return i;
            }
        }
        return -1;
    }
    else {
        return $.inArray(value, array);
    }
}
//获取数组中第一个匹配的值
$.getValueByArray = function (value, array, fn) {
    var index = $.inArrayEx(value, array, fn);
    if (index >= 0) {
        return array[index];
    }
    return null;
}

//循环数组
$.loop = function (array, fn, type, si, ei) {
    if (array) {
        type = type == false ? false : true;
        if (type) {
            si = si || 0;
            ei = ei || array.length;
            for (var i = si; i < ei; i++) {
                if (fn(array[i], i) == false) {
                    break;
                }
            }
        }
        else {
            si = si || array.length - 1;
            ei = ei || 0;
            for (var i = si; i >= ei; i--) {
                if (fn(array[i], i) == false) {
                    break;
                }
            }
        }
    }
}

//过滤数组
$.filterArray = function (array, fn, filterType) {
    var temp = [];
    filterType = filterType == false ? false : true;
    for (var i = 0; i < array.length; i++) {
        var result = fn(array[i],i);
        if (filterType) {
            if (result == true) {
                temp.push(array[i]);
            }
        }
        else {
            if (result == false) {
                temp.push(array[i]);
            }
        }
    }
    return temp;
}

//递归调用函数
$.Recursive = function (obj, property, callback, pObject, args, level, index) {
    var level = level || 0;
    var index = index || 0;
    if (obj) {
        var result = { "stop": false, "customer": args };
        pObject = pObject ? pObject : null;
        callback(obj, pObject, result, level, index);
        if (result.stop == true) {
            return false;
        }
        var children = null;
        if ($.isFunction(property)) {
            children = property(obj, pObject);
        }
        else if (typeof (property) == "string") {
            children = obj[property];
        }
        if (children) {
            if ($.isArray(children)) {
                for (var i = 0; i < children.length; i++) {
                    var c = children[i];
                    if ($.Recursive(c, property, callback, obj, result.customer, (level + 1), i) == false) {
                        return false;
                    }
                }
            }
            else {
                if ($.Recursive(children, property, callback, obj, result.customer, (level + 1), 0) == false) {
                    return false;
                }
            }
        }
    }
}
//转换成数组
$.convertArray = function (obj) {
    if ($.isArray(obj)) {
        return obj;
    }
    else {
        var temp = [];
        temp.push(obj);
        return temp;
    }
}

//jquery扩展函数 结束============================

$(document).ready(function () {
    $.controlInit = function (controlName, jqObject, method, args) {
        if (typeof (method) == "string") {
            if ($.isFunction($.fn[controlName].methods[method])) {
                //alert($.fn[controlName].methods[method](jqObject, args))
                return $.fn[controlName].methods[method](jqObject, args);
            }
            return;
        }
        var options = method || {};
        method = "init";
        return $.fn[controlName].methods["init"](jqObject, options);
    };

    var list = {};
    /*$.fn.dropAction = function (dropEnter, dragLeave) {
    var jqobj = this;
    jqobj.each(function (i) {
    var obj = jqobj.eq(i);
    obj.data("dropEnter", dropEnter);
    obj.data("dragLeave", dragLeave);
    });
    };*/
    $.emptySelected = function () {
        try {
            if (document.selection) {
                document.selection.empty();
            }
            else if (window.getSelection) {
                window.getSelection().removeAllRanges()
            }
        }
        catch (ex) { }
    }
});

//编辑器
$.editor = {
    text: {
        init: function (container, options) {
            var input = $("<input class='grid-edit grid-edit-input' type='text'>").appendTo(container);
            return input
        },
        getValue: function (target) {
            var val = target.val();
            return val;
        },
        setValue: function (target, value) {
            target.val(value);
        },
        resize: function (target, size) {
            if (size.width) {
                target.width(size.width);
            }
            if (size.height) {
                target.height(size.height);
            }
        }
    }
}

//创建属性框的的数据源
function createPropertyData(properties, onwer, callBack, readonly) {
    var rows = [];
    if (properties) {
        var propertyGroup = (properties && properties.PropertyGroup) ? $.convertArray(properties.PropertyGroup) : [];
        properties.PropertyGroup = propertyGroup;
        var rules = properties.Rules || null;
        var _switch = properties.Switch;
        for (var i = 0; i < propertyGroup.length; i++) {
            var group = propertyGroup[i];
            var propertys = (group.Property) ? $.convertArray(group.Property) : [];
            group.Property = propertys;
            for (var n = 0; n < propertys.length; n++) {
                var property = propertys[n];
                if (!property.uqkey) {
                    property.uqkey = new Date().getTime();
                }
                var s = property;
                var value = s.text || "";
                if (s.defaultValue) {
                    if (!s.text) {
                        s.text = s.defaultValue;
                        value = s.text;
                    }
                }
                if (typeof (value) == "string") {
                    //value = value.replace(/</g, "&lt");
                    //value = value.replace(/>/g, "&gt");
                }
                var editor = s.type;
                var editOptions = {};
                try {
                    if (s.readonly == "true") {
                        editor = "readonly";
                    }
                    else {
                        switch (s.type) {
                            case "list":
                                if (!readonly) {
                                    editor = "combobox";
                                    editOptions.editable = false;
                                    if (s.multiple == "true") {
                                        editOptions.multiple = true;
                                    }
                                    var dsname = s.rule;
                                    if (dsname) {
                                        var rule = rules[dsname];
                                        s.listOptions = rule;
                                        var options = rule.Option ? $.convertArray(rule.Option) : [];
                                        rule.Option = options;
                                        editOptions.data = [];
                                        var selectedVal = property.text || null;
                                        for (var k = 0; k < options.length; k++) {
                                            var option = options[k];
                                            if (!selectedVal) {
                                                editOptions.data.push({ "text": option.text, "value": option.key, "selected": k == 0 });
                                                if (k == 0) {
                                                    value = option.key;
                                                }
                                            }
                                            else {
                                                editOptions.data.push({ "text": option.text, "value": option.key, "selected": selectedVal == option.key });
                                                value = selectedVal;
                                            }
                                        }
                                    }
                                }
                                else {
                                    editor = "readonly";
                                    //s.readonly = "true";
                                }
                                break;
                            case "bool":
                                if (!readonly) {
                                    editor = "checkbox";
                                    editOptions.on = "true";
                                    editOptions.off = "false";
//                                    value = s.text;
//                                    if (s.text == "true") {
//                                        value = true;
//                                    }
//                                    else {
//                                        value = false;
//                                    }
                                }
                                else {
                                    editor = "readonly";
                                    //s.readonly = "true";
                                }
                                break;
                            case "logic":
                                if (!readonly) {
                                    editor = "checkbox";
                                    editOptions.on = "1";
                                    editOptions.off = "0";
                                }
                                else {
                                    editor = "readonly";
                                }
                                break;
                            case "url":
                                if (readonly) {
                                    editOptions.readonly = true;
                                }
                                if (s.rule) {
                                    editOptions.url = replaceString(s.rule);
                                }
                                else if (s["switch"]) {
                                    editOptions.url = function (rows) {
                                        var _case = _switch[s["switch"]].Case;
                                        _case = $.isArray(_case) ? _case : [_case];
                                        var returnVal = "";
                                        for (var i = 0; i < _case.length; i++) {
                                            var c = _case[i];
                                            var exp = c.Expression;
                                            var reg = /\{@([^{@}]+)\}/g;
                                            var result = reg.exec(exp);
                                            if (result) {
                                                var showname = result[1];
                                                if (showname) {
                                                    var row = $.getValueByArray(showname, rows, function (v1, v2) {
                                                        return v1 == v2.name;
                                                    });
                                                    if (row) {
                                                        exp = exp.replace(reg, "row");
                                                    }
                                                }
                                            }
                                            try {
                                                var mark = eval(exp);
                                                if (mark) {
                                                    returnVal = c.Value;
                                                    break;
                                                }
                                            }
                                            catch (ex) { }
                                        }
                                        if (!returnVal) {
                                            var _default = _switch[s["switch"]].Default;
                                            if (_default) {
                                                returnVal = _default.Value;
                                            }
                                            else {
                                                alert("未找到匹配的项");
                                            }
                                        }
                                        return returnVal;
                                    }
                                }
                                if (s.windowLevel) {
                                    editOptions.windowLevel = s.windowLevel;
                                }
                                if (s.dialogWidth) {
                                    editOptions.width = s.dialogWidth;
                                }
                                if (s.dialogHeight) {
                                    editOptions.height = s.dialogHeight;
                                }
                                if (s.minimizable == "true") {
                                    editOptions.minimizable = true;
                                }
                                if (s.maximized == "true") {
                                    editOptions.maximized = true;
                                }
                                editOptions.resizable = s.resizable != "false" ? true : false;
                                editOptions.draggable = s.draggable != "false" ? true : false;
                                break;
                            default:
                                if (!readonly) {
                                    editor = s.type;
                                }
                                else {
                                    editor = "readonly";
                                    //s.readonly = "true";
                                }
                                break;
                        }
                        if (editor == "text") {
                            editor = "validatebox";
                            if (s.required == "true") {
                                editOptions.required = true;
                            }
                            var rs = [];
                            if (s.rule != "") {
                                rs.push("\"regExp[" + s.rule + "]\"");
                            }
                            if (window["propertyChangeCheck"] && $.isFunction(window["propertyChangeCheck"])) {
                                rs.push("\"customer['propertyChangeCheck','" + s.name + "']\"")
                            }
                            editOptions.validType = 'many[' + rs.join(",") + ']';
                        }
                        else if (editor == "number") {
                            editor = "numberbox";
                            if (s.required == "true") {
                                editOptions.required = true;
                            }
                        }
                    }
                }
                catch (ex) {
                    alert(ex.description);
                    continue;
                }

                if ($.isFunction(callBack)) {
                    value = callBack(value, property);
                    if (value == null) {
                        value = "";
                    }
                }

                var row = null;
                row = $.extend({}, property, { "group": group.showname, "value": value, "editor": { "type": editor, "options": editOptions} });
                rows.push(row);
            }
        }
    }
    return rows;
}

//转换XML
function toXml(v, tag) {
    var value = "";
    if ($.isArray(v)) {
        for (var i = 0, n = v.length; i < n; i++) {
            if (typeof (v[i]) == "string") {
                value += "<" + tag + ">" + v[i] + "</" + tag + ">"
            } else {
                value += toXml(v[i], tag);
            }
        }
    }
    else if (typeof (v) == "object") {
        value += "<" + tag;
        var text = "";
        var hasChild = false;
        for (var m in v) {
            if ($.isFunction(v[m]) || m == "uqkey") {
                continue;
            }
            if (m == "text") {
                text = (v[m] == undefined) ? "" : v[m].toString();
                continue;
            }
            if (/^[a-z]+$/.test(m.charAt(0))) {
                value += " " + m + "=\"" + (v[m] ? v[m].toString() : "") + "\"";
            } else {
                hasChild = true;
            }
        }
        value += hasChild ? ">" : ((text == "") ? "/>" : ("><![CDATA[" + text + "]]></" + tag + ">"));
        if (hasChild) {
            for (var m in v) {
                if (/^[A-Z]+$/.test(m.charAt(0))) {
                    value += toXml(v[m], m);
                }
            }
            value += "</" + tag + ">";
        }
    }
    else {
        value += "<" + tag + "><![CDATA[" + v + "]]></" + tag + ">";
    }
    return value;
}
function deleteJsObjectProperty(obj, properties) {
    properties = properties || [];
    for (var i = 0; i < properties.length; i++) {
        var pro = properties[i];
        if (obj[pro]) {
            delete obj[pro];
        }
    }
}

function loadingLayout(fn, text, container) {
    loading(text, container);
    window.setTimeout(function () {
        try {
            fn();
        }
        catch (ex) {
            alert(ex);
        }
        finally {
            loaded();
        }
    }, 0);
}

function loading(text, container) {
    var body = container && container.length > 0 ? container : $("body");
    var mask = $("<div class=\"datagrid-mask\" style=\"display:block\"></div>").appendTo(body);
    var text = text || "数据加载中...";
    var msg = $("<div class=\"datagrid-mask-msg\" style=\"display:block\"></div>").html(text).appendTo(body);
    if (mask.length) {
        mask.css({ width: body.width(), height: body.height() });
        msg.css("left", (body.width() - msg.outerWidth()) / 2);
        msg.css("top", (body.height() - msg.outerHeight()) / 2);
    }
}
function loaded() {
    var body = $("body");
    body.find("div.datagrid-mask-msg").remove();
    body.find("div.datagrid-mask").remove();
}




$.copyTo = function (options) {
    var text = $("#copyTextBox");
    if (text.length <= 0) {
        text = $("<textarea id=\"copyTextBox\" style=\"display:none;position:absolute;z-index:100000;top:0px;left:0px\"></textarea>").appendTo($("body"));
    }
    function __ctrlv(evt) {
        if (evt.ctrlKey && evt.keyCode == 86) {
            if ($.isFunction(options.onBeforeCopy)) {
                if (options.onBeforeCopy() == false) {
                    return false;
                }
            }
            if (evt.target.tagName != "INPUT" && evt.target.tagName != "TEXTAREA") {
                text.fadeTo(10, 0);
                window.focus();
                text.focus().select();
                window.setTimeout(dealwithData, 10);
            }
        }
    }
    $("body").bind("keydown", __ctrlv);
    function dealwithData() {
        text.blur();
        text.hide();
        try {
            if ($.isFunction(options.onCopySuccess)) {
                //alert(text.val());
                options.onCopySuccess(text.val());
                if (options.one == true) {
                    $("body").unbind("keydown", __ctrlv);
                }
            }
        }
        catch (ex) {
        }
        finally {
        }
    }
}

var isImporting = false;
//将剪贴板数据导入到EASYUI DATAGRID;
function clipboardImportDataGrid(datagrid, gridType, onRowComplete, onAllComplete, isHead, roleFn) {
    gridType = gridType || "datagrid";
    $.copyTo({
        one:true,
        onCopySuccess: function (data) {
            var str = data;
            var importRows = analysisData(data);
            loadingLayout(function () {
                if (isImporting) {
                    return;
                }
                isImporting = true;
                var options = datagrid[gridType]("options");
                var frozenColumns = options.frozenColumns;
                var columns = options.columns;
                frozenColumns = frozenColumns.length > 0 ? frozenColumns[frozenColumns.length - 1] : [];
                columns = columns ? columns[columns.length - 1] : [];
                var temp = [];
                var head = [];
                for (var i = 0; i < importRows.length; i++) {
                    var row = importRows[i];
                    if (isHead) {
                        if (i == 0) {
                            head = row;
                            continue;
                        }
                    }
                    var rowData = {};
                    for (var n = 0; n < row.length; n++) {
                        var col = row[n];
                        var colName = head[n];
                        var gridColumn = $.getValueByArray(colName, columns, function (v1, v2) { return v1 == v2.title });
                        if (!gridColumn) {
                            gridColumn = $.getValueByArray(colName, frozenColumns, function (v1, v2) { return v1 == v2.title });
                        }
                        if (gridColumn) {
                            rowData[gridColumn.field] = col;
                        }
                    }
                    var result = true;
                    if (onRowComplete) {
                        result = onRowComplete(rowData, i);
                    }
                    if (result != false) {
                        temp.push(rowData);
                    }
                }
                if (onAllComplete) {
                    onAllComplete(temp);
                }
                else {
                    var data = datagrid[gridType]("getData");
                    var rows = $.isArray(data) ? data : data.rows;
                    $.merge(rows, temp);
                    datagrid[gridType]("loadData", data);
                }
                isImporting = false;

            }, "正在处理数据");
        }
    });
}